package com.fafa.pos.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.*;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.*;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.*;
import com.fafa.pos.R;
import com.fafa.pos.biz.ComplexBiz;
import com.fafa.pos.dao.DBUtil;
import com.fafa.pos.dao.IConfigDao;
import com.fafa.pos.dao.IConsumeInfoDao;
import com.fafa.pos.dao.impl.ConfigDaoImpl;
import com.fafa.pos.dao.impl.ConsumeInfoDaoImpl;
import com.fafa.pos.pojo.Config;
import com.fafa.pos.pojo.ConsumeInfo;
import com.fafa.pos.util.*;
import com.fafa.pos.vo.CurUser;
import com.fafa.pos.vo.Status;
import com.fafa.pos.vo.UpdateInfo;
import com.fafa.pos.vo.WSResult;
import com.nld.cloudpos.aidl.AidlDeviceService;
import com.nld.cloudpos.aidl.printer.AidlPrinter;
import com.nld.cloudpos.aidl.printer.AidlPrinterListener;
import com.nld.cloudpos.aidl.printer.PrintItemObj;
import com.nld.cloudpos.aidl.rfcard.AidlRFCard;
import com.nld.cloudpos.data.PrinterConstant;
import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

public class MoreActivity extends TitleActivity {

    private SharedPreferencesHelper sharedPreferencesHelper;
    private String showUserName;

    //dao相关
    private DBUtil dbUtil;
    private IConsumeInfoDao consumeInfoDao;
    private IConfigDao configDao;

    //view相关
    private TextView userName;
    private TextView todayGathering;
    private RelativeLayout todayGatheringDetail;
    private Button reLogin;
    private Switch offLine;
    private RelativeLayout downloadData;
    private RelativeLayout loading;
    private RelativeLayout uploadOffLineData;
    private RelativeLayout setQuick;
    private RelativeLayout rePrint;
    private Switch defaultPrintSwitch;
    private RelativeLayout upgrade;
    private RelativeLayout errorUpload;

    /**
     * newLand服务连接
     */
    private final String TAG = "newland";
    private AidlDeviceService aidlDeviceService;
    private AidlPrinter aidlPrinter ;
    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.d(TAG, "bind device service");
            aidlDeviceService = AidlDeviceService.Stub.asInterface(service);
            try {
                aidlPrinter = AidlPrinter.Stub.asInterface(aidlDeviceService.getPrinter());
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.d(TAG, "unbind device service");
            aidlDeviceService = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_more);


        //初始化标题栏
        setTitle("功能设置");
        showBackwardView(R.string.text_back, true);
        showForwardView(R.string.text_back, false);

        //设置状态栏和标题栏同色
        Window window = this.getWindow();
        //取消设置透明状态栏,使 ContentView 内容不再覆盖状态栏
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);

        //需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(getResources().getColor(R.color.LoginBlue));

        ViewGroup mContentView = (ViewGroup) this.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            //注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 预留出系统 View 的空间.
            ViewCompat.setFitsSystemWindows(mChildView, true);
        }
        //加入activity管理
        MyActivityManager.getInstance().addActivity(this);

        initDB();
        initView();
        initEvent();


        bindService(new Intent("nld_cloudpos_device_service"), serviceConnection,
                Context.BIND_AUTO_CREATE);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
    }

    /**
     * 初始化dao层实例
     */
    private void initDB(){
        dbUtil = new DBUtil(getApplicationContext().getFilesDir().getAbsoluteFile()+"/pos.db");
        consumeInfoDao = new ConsumeInfoDaoImpl(dbUtil);
        configDao = new ConfigDaoImpl(dbUtil);

        /*dbUtil.clearTable("T_CONSUMEINFO");
        //造点儿假数据
        for(int i = 0;i<20;i++){
            ConsumeInfo consumeInfo = new ConsumeInfo();
            consumeInfo.setId(UUID.randomUUID().toString().replaceAll("-",""));
            consumeInfo.setMoney("0.01");
            consumeInfo.setCardCode("3088065219");
            consumeInfo.setDate(DateUtil.getCurDateStr("yyyy-MM-dd HH:mm:ss"));
            consumeInfo.setIsUpLoad(""+(new Random().nextInt(15)/10));
            consumeInfoDao.saveConsumeInfo(consumeInfo);
        }*/
    }
    private void initView() {

        sharedPreferencesHelper = new SharedPreferencesHelper(
                MoreActivity.this, "PosUserInfo");//实例化sharedPreferencesHelper工具类
        showUserName = sharedPreferencesHelper.getSharedPreference("userName", "").toString().trim();//获取userName

        userName = (TextView) findViewById(R.id.userName);
        todayGathering = (TextView) findViewById(R.id.todayGathering);
        todayGatheringDetail = (RelativeLayout) findViewById(R.id.todayGatheringDetail);
        offLine = (Switch) findViewById(R.id.offLine);
        downloadData = (RelativeLayout) findViewById(R.id.downloadData);
        reLogin = (Button) findViewById(R.id.reLogin);
        loading = (RelativeLayout) findViewById(R.id.loading);
        uploadOffLineData = (RelativeLayout) findViewById(R.id.uploadOffLineData);
        setQuick = (RelativeLayout) findViewById(R.id.setQuick);
        rePrint = (RelativeLayout) findViewById(R.id.rePrint);
        defaultPrintSwitch = (Switch) findViewById(R.id.defaultPrintSwitch);
        upgrade = (RelativeLayout) findViewById(R.id.upgrade);
        errorUpload = (RelativeLayout) findViewById(R.id.errorUpload);


        userName.setText(showUserName);

        //设置今日收款金额
        double total = 0.00;
        List<ConsumeInfo> consumeInfoList = consumeInfoDao.getCurDayConsumeInfo();
        if(consumeInfoList!=null){
            for (ConsumeInfo consumeInfo:consumeInfoList) {
                total+=Double.parseDouble(consumeInfo.getMoney());
            }
            DecimalFormat df = new DecimalFormat("0.00");
            todayGathering.setText("¥"+df.format(total));
        }
        //离在线模式
        if(Status.getStatus().isOffLine()){
            offLine.setChecked(true);
        }else{
            offLine.setChecked(false);
        }

        Config config = configDao.getConfig();
        //默认打印小票模式
        if("true".equals(config.getProperties().get("defaultPrint"))){
            defaultPrintSwitch.setChecked(true);
        }else{
            defaultPrintSwitch.setChecked(false);
        }
    }
    private void initEvent() {

        //软件升级
        upgrade.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upgradeDo();
            }
        });

        //小票重印
        rePrint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Config config = configDao.getConfig();
                //打印
                String[] printInfo = config.getProperties().get("PRINT_ACCT_INFO").split("\n");
                final List<PrintItemObj> data = new ArrayList<PrintItemObj>();

                data.add(new PrintItemObj("索迪斯餐厅", PrinterConstant.FontScale.FONTSCALE_DW_DH, PrinterConstant.FontType.FONTTYPE_S, PrintItemObj.ALIGN.CENTER, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("单据号:" + config.getProperties().get("SHEET_CODE"), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("POS机号:"+config.getProperties().get("posCode"), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("===============================", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("总共消费:"+config.getProperties().get("payMoney"), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("扣款账户", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                for (String aPrintInfo : printInfo) {
                    data.add(new PrintItemObj(aPrintInfo, PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                }
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("===============================", PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("消费时间:" + config.getProperties().get("payDate"), PrinterConstant.FontScale.FONTSCALE_W_H, PrinterConstant.FontType.FONTTYPE_N, PrintItemObj.ALIGN.LEFT, false, 6));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));
                data.add(new PrintItemObj("\r"));

                if (aidlPrinter != null) {
                    try {
                        aidlPrinter.open();

                        aidlPrinter.printText(data);

                        aidlPrinter.start(new AidlPrinterListener.Stub() {

                            @Override
                            public void onPrintFinish() throws RemoteException {
                                Log.e(TAG, "打印结束");
                            }

                            @Override
                            public void onError(int errorCode) throws RemoteException {
                                Log.e(TAG, "打印异常");
                            }
                        });
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                } else {
                    Log.e(TAG, "未检测到打印机模块访问权限");
                }
            }
        });

        //上传销售数据页面跳转
        uploadOffLineData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MoreActivity.this,OffLineDataUploadActivity.class);
                startActivity(intent);
            }
        });

        //今日收款详细按钮跳转事件
        todayGatheringDetail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MoreActivity.this,GatheringDetailActivity.class);
                startActivity(intent);
            }
        });

        //设置菜单快捷输入键
        setQuick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(MoreActivity.this,QuickKeySetActivity.class);
                startActivity(intent);

            }
        });

        //默认打印小票模式切换
        defaultPrintSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Config config = configDao.getConfig();
                config.getProperties().put("defaultPrint",isChecked+"");
                configDao.saveConfig(config);
            }
        });

        //离线、在线模式切换
        offLine.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Status.getStatus().setOffLine(isChecked);
            }
        });

        //下载基础数据
        downloadData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                msgHandler.sendEmptyMessage(2);

                ComplexBiz complexBiz1 = new ComplexBiz(dbUtil);
                String errorMessage = complexBiz1.downloadData();

                if(errorMessage!=null){//下载数据失败
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = errorMessage;
                    msgHandler.sendMessage(msg);
                }
                msgHandler.sendEmptyMessage(2);
                AlertDialog.Builder builder = new AlertDialog.Builder(MoreActivity.this);
                builder.setTitle("下载成功").setPositiveButton("确定",null);
                builder.show();
            }
        });
        //错误上传：上传数据库
        errorUpload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final ProgressDialog pd = new ProgressDialog(MoreActivity.this);
                pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                pd.setTitle("正在上传错误数据...");
                pd.show();

                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        DataInputStream in = null;
                        OutputStream out = null;
                        HttpURLConnection conn = null;
                        JSONObject resposeTxt = null;
                        InputStream ins = null;
                        ByteArrayOutputStream outStream = null;
                        try {


                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd--HHmmss");
                            String dateStr = sdf.format(new Date());
                            Config config = configDao.getConfig();
                            String path = File.separator+"POS"+File.separator+dateStr.split("--")[0];
                            String fileName = config.getProperties().get("posCode")+"-"+dateStr.split("--")[1]+".db";

                            URL url = new URL("http://139.196.170.149:9333/uploadFile?path="+path+"&fileName="+fileName);
                            conn = (HttpURLConnection) url.openConnection();
                            // 发送POST请求必须设置如下两行
                            conn.setDoOutput(true);
                            conn.setUseCaches(false);
                            conn.setRequestMethod("POST");
                            conn.setRequestProperty("Content-Type", "text/html");
                            conn.setRequestProperty("Cache-Control", "no-cache");
                            conn.setRequestProperty("Charsert", "UTF-8");
                            conn.setChunkedStreamingMode(0); //设置流的大小，当流超过这个数值 则 发送
                            conn.connect();
                            conn.setConnectTimeout(10000);
                            out = conn.getOutputStream();

                            File file = new File(getApplicationContext().getFilesDir().getAbsoluteFile()+"/pos.db");

                            pd.setMax((int)file.length());

                            in = new DataInputStream(new FileInputStream(file));

                            int progress = 0;
                            int bytes = 0;
                            byte[] buffer = new byte[1024];
                            while ((bytes = in.read(buffer)) != -1) {
                                out.write(buffer, 0, bytes);
                                progress+=bytes;
                                pd.setProgress(progress);
                            }
                            out.flush();

                            // 返回流
                            if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                                Message msg = new Message();
                                msg.what = 1;
                                msg.obj = "上传成功";
                                msgHandler.sendMessage(msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        } finally {
                            try {
                                if (in != null) {
                                    in.close();
                                }
                                if (out != null) {
                                    out.close();
                                }
                                if (ins != null) {
                                    ins.close();
                                }
                                if (outStream != null) {
                                    outStream.close();
                                }
                                if (conn != null) {
                                    conn.disconnect();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            pd.dismiss();

                        }
                    }
                }).start();
            }
        });

        //重新登录
        reLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //MyActivityManager.getInstance().reLogin();
                Intent intent = new Intent(MoreActivity.this,LoginActivity.class);
                startActivity(intent);
            }
        });
    }

    /**
     * 软件升级
     */
    private UpdateInfo updateInfo;
    private void upgradeDo() {
        //1.检查版本
        updateInfo = getUpdateInfo();

        //2.版本不同,升级
        String systemVersionName = getVersionName();

        if(systemVersionName!=null){
            if(systemVersionName.equals(updateInfo.getVersionName())){
                Message msg = new Message();
                msg.what = 1;
                msg.obj = "暂无更新";
                msgHandler.sendMessage(msg);
            }else{
                //弹框是否下载apk
                showUpgradeDialog();
            }
        }
    }

    /**
     * 获得最新版本信息
     * @return
     */
    private UpdateInfo getUpdateInfo() {

        UpdateInfo updateInfo = null;
        Config config = configDao.getConfig();
        SoapObject so = WebServiceUtil.getResponse(config,"GetUpgradeInfo",null,1000*15);
        if(so!=null){
            SoapPrimitive sp = (SoapPrimitive) so.getProperty("GetUpgradeInfoResult");
            WSResult wsResult = WebServiceValueCastUtil.cast(sp.toString());
            if(wsResult.getResultCode()==0){
                updateInfo = new UpdateInfo();
                updateInfo.setVersionName(wsResult.getResultValues().get("VERSION").toString());
                updateInfo.setUrl(wsResult.getResultValues().get("URL").toString());
                updateInfo.setDescription(wsResult.getResultValues().get("DESCRIPTION").toString());

            }else{
                Message msg = new Message();
                msg.what = 1;
                msg.obj=wsResult.getResultValues().get("message").toString();
                msgHandler.sendMessage(msg);
            }

        }else{
            Message msg = new Message();
            msg.what = 1;
            msg.obj="获得最新版本信息失败";
            msgHandler.sendMessage(msg);
        }

        return updateInfo;
    }

    /**
     * 获得当前程序的版本号
     * @return  versionName
     */
    private String getVersionName() {

        PackageManager packageManager = null;
        PackageInfo packageInfo = null;
        try {
            //获得PackageManager的实例
            packageManager = getPackageManager();
            //getPackgeNage()是当前类的包名，0代表获得版本信息
            packageInfo = packageManager.getPackageInfo(getPackageName(),0);
            return  packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return  null;
    }

    /**
     * 是否更新
     */
    private void showUpgradeDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(MoreActivity.this);
        builder.setTitle("版本升级")
                .setMessage(updateInfo.getDescription())
                .setNegativeButton("取消",null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        downloadAPK();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 下载apk
     */
    private void downloadAPK() {

        //1.构造下载进度条
        final ProgressDialog pd = new ProgressDialog(MoreActivity.this);
        pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pd.setMessage("正在下载更新");
        pd.show();
        //2.开启下载线程
        new Thread(new Runnable() {
            @Override
            public void run() {

                    File file = getFileFromServer(updateInfo.getUrl(),pd);
                    pd.dismiss();//结束掉下载进度条
                    if(file!=null){
                        //安装apk
                        installAPK(file);
                        //程序一定一定要关掉，不然安装完成后，不会出现取消，打开按钮
                        MyActivityManager.getInstance().exit();
                    }else{//下载失败
                        Message msg = new Message();
                        msg.what = 1;
                        msg.obj="下载新本失败";
                    }
            }
        }).start();
    }



    /**
     * 从服务器下载apk
     * @param path  url
     * @param pd    下载进度条
     * @return
     */
    private File getFileFromServer(String path,ProgressDialog pd) {

        //MEDIA_MOUNTED 存储媒体已经挂载，并且挂载点可读/写。
        //判断是否有SD卡
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){

            InputStream is = null;
            BufferedInputStream bis = null;
            FileOutputStream fos = null;
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(1000*15);//设置连接超时

                //进度条设置长度
                pd.setMax(conn.getContentLength());

                //输出apk文件到磁盘
                File file = new File(Environment.getExternalStorageDirectory(),"update.apk");
                is = conn.getInputStream();
                bis = new BufferedInputStream(is);
                fos = new FileOutputStream(file);

                byte[] buf = new byte[1024];
                int len = -1;
                int total = 0;
                while((len = bis.read(buf))!=-1){
                    //写文件
                    fos.write(buf,0,len);
                    total += len;
                    //当前下载量
                    pd.setProgress(total);
                }
                return  file;

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    if(fos!=null){
                        fos.close();
                        fos = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    try {
                        if(bis!=null){
                            bis.close();
                            bis = null;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }finally {
                        try {
                            if(is!=null){
                                is.close();
                                is = null;
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            return  null;
        }else{
            return null;
        }
    }

    /**
     * 安装apk
     * @param file
     */
    private void installAPK(File file) {
        Intent intent = new Intent();
        //执行动作
        intent.setAction(Intent.ACTION_VIEW);
        //打开文件的类型        ".apk",    "application/vnd.android.package-archive"
        intent.setDataAndType(Uri.fromFile(file),"application/vnd.android.package-archive");
        startActivity(intent);

    }
    private Handler msgHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 1://消息提示
                    Toast toast = Toast.makeText(MoreActivity.this,msg.obj.toString(),Toast.LENGTH_SHORT);
                    MyToast.showMyToast(toast,1000);
                    break;
                case 2://下载view显示/不显示切换
                    if(loading.getVisibility()==View.INVISIBLE){
                        loading.setVisibility(View.VISIBLE);
                    }else{
                        loading.setVisibility(View.INVISIBLE);
                    }
                    break;
                case 3:
                    showUpgradeDialog();
                    break;
            }
        }
    };
}
